package cm.example.shoppingplatformspringboot.controller;

import cm.example.shoppingplatformspringboot.service.AlipayService;
import cm.example.shoppingplatformspringboot.service.OrderService;
import cm.example.shoppingplatformspringboot.utils.AlipayConfig;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
public class AlipayController {
    @Resource
    private AlipayService alipayService;
    @Resource
    private OrderService orderService;

    @PostMapping("/pay")
    public String createPayOrder(String orderNo, String subject) {
        return alipayService.createAlipayOrder(orderNo, subject);
    }

    /**
     * 支付宝异步通知接口
     * 支付宝服务器会主动发送POST请求到这个接口
     *
     * @return 处理结果
     */
    @PostMapping("/notify")
    public String notify(HttpServletRequest request) {
        try {
            Map<String, String> params = convertRequestToMap(request);

            // 1. 验证签名
            boolean signValid = AlipaySignature.rsaCheckV1(
                    params,
                    AlipayConfig.ALIPAY_PUBLIC_KEY,
                    "UTF-8",
                    "RSA2");

            if (!signValid) return "failure";

            // 2. 处理业务逻辑
            String tradeStatus = params.get("trade_status");
            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                String orderNo = params.get("out_trade_no");
                orderService.updateOrderPayTime(orderNo);
            }

            return "success";
        } catch (AlipayApiException e) {
            return "failure";
        }
    }

    // 转换请求参数

    @NotNull
    private Map<String, String> convertRequestToMap(@NotNull HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String key : requestParams.keySet()) {
            params.put(key, String.join(",", requestParams.get(key)));
        }
        return params;
    }
}